package com.business_clean.app.base;

import static me.hgj.mvvmhelper.ext.GetViewModelExtKt.getVmClazz;
import static me.hgj.mvvmhelper.ext.ViewBindUtilKt.inflateBinding;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.business_clean.R;
import com.business_clean.app.config.Constant;
import com.business_clean.app.config.ConstantMMVK;
import com.business_clean.app.config.OnJsBridge;
import com.business_clean.app.uitl.MMKVHelper;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.DefaultWebClient;
import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebViewClient;

import me.hgj.mvvmhelper.base.BaseViewModel;
import me.hgj.mvvmhelper.ext.LogExtKt;

public abstract class BaseAgentWebActivity<VM extends BaseViewModel, VB extends ViewBinding> extends AppCompatActivity {

    private String TAG = "BaseAgentWebActivity";
    protected AgentWeb.PreAgentWeb mAgentWeb;
    protected VM viewModel;
    protected VB mDatabind;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化ViewBinding
        setContentView(initViewDataBind());
        initView(savedInstanceState);
        onBindViewClick();
        initObserver();
        // 初始化ViewModel
        viewModel = createViewModel();
        initAgentWeb();
    }

    private void initAgentWeb() {
        //获取apptoken
        String token = MMKVHelper.getString(ConstantMMVK.TOKEN);

        if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(getUrl())) {
            //设置cookie之前先清楚之前的 设置 重新
            AgentWebConfig.removeAllCookies();
            AgentWebConfig.syncCookie(getUrl(), "xmjz_token=" + token);
            String tagCookie = AgentWebConfig.getCookiesByUrl(getUrl());//获取当前设置的cookie
            LogUtils.e("AgentWeb Token - " + tagCookie);
        }
        LogUtils.e("AgentWeb url - " + getUrl());
        // 初始化AgentWeb
        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(getAgentWebParent(), new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
                .useDefaultIndicator()
                .setWebViewClient(mWebViewClient)
                .setWebChromeClient(mWebChromeClient)
                .additionalHttpHeader(getUrl(), "xmjztoken", token)
                .additionalHttpHeader(getUrl(), "xmjzplatform", "android")
                .additionalHttpHeader(getUrl(), "xmjzversion", AppUtils.getAppVersionName())
                .setMainFrameErrorView(R.layout.agentweb_error_page, -1)//参数1是错误显示的布局，参数2点击刷新控件ID -1表示点击整个布局都刷新， AgentWeb 3.0.0 加入。
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)     //严格模式 Android 4.2.2 以下会放弃注入对象 ，使用AgentWebView没影响。
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
                .interceptUnkownUrl()
                .createAgentWeb()
                .ready();
        //设置交互
        mAgentWeb.get().getJsInterfaceHolder().addJavaObject(Constant.JS_SPACE_NAME, getOnJsBridge());
        //设置userAgent
        WebSettings webSettings = mAgentWeb.get().getAgentWebSettings().getWebSettings();
        webSettings.setUserAgentString(getWebViewUserAgent(webSettings));
        //跳转
        mAgentWeb.go(getUrl());
    }

    /**
     * 设置Agent的UserAgent
     *
     * @param webSettings
     * @return
     */
    private String getWebViewUserAgent(WebSettings webSettings) {
        String userAgent = "XmjzCapp/" + AppUtils.getAppVersionName() + " " + webSettings.getUserAgentString();
        return userAgent;
    }


    /**
     * 交互回调 ，继承者实现
     *
     * @return
     */
    protected OnJsBridge getOnJsBridge() {
        return new OnJsBridge(mAgentWeb.get());
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        //拦截初次加载的黑名单url
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            LogExtKt.logE("shouldInterceptRequest ", TAG);
            return super.shouldInterceptRequest(view, url);
        }

        //拦截初次加载的黑名单url
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            LogExtKt.logE("shouldInterceptRequest ", TAG);
            return shouldInterceptRequest(view, request.getUrl().toString());
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            LogExtKt.logE("shouldOverrideUrlLoading ", TAG);
            return super.shouldOverrideUrlLoading(view, url);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            LogUtils.e("shouldOverrideUrlLoading ", TAG);
            return super.shouldOverrideUrlLoading(view, request);
        }
    };

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        final View[] customView = {null};

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            // 打印H5日志到Android端的Logcat
            LogExtKt.logE("H5_LOG -> " + consoleMessage.message(), TAG);
            return true;
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
//            if (my_header_view != null) {
//                my_header_view.setMiddleText(TextUtils.isEmpty(getBarTitle()) ? title : getBarTitle());
//            }
//
//            BackHeaderView realHeaderVew = getRealHeaderVew();
//            if (realHeaderVew != null) {
//                realHeaderVew.setMiddleText(TextUtils.isEmpty(getBarTitle()) ? title : getBarTitle());
//            }
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            customView[0] = view;
//            if(mFrameLayout != null) {
//                mFrameLayout.addView(customView[0]);
//            }
        }

        @Override
        public void onHideCustomView() {
            super.onHideCustomView();
//            if(customView[0] != null && customView[0].isAttachedToWindow() && mFrameLayout != null) {
//                mFrameLayout.removeView(customView[0]);
//            }
        }
    };

    @Override
    public void onPause() {
        if (mAgentWeb != null) {
            mAgentWeb.get().getWebLifeCycle().onPause();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        if (mAgentWeb != null) {
            mAgentWeb.get().getWebLifeCycle().onResume();
        }
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 销毁AgentWeb
        if (mAgentWeb != null) {
            mAgentWeb.get().destroy();
        }
    }


    private VM createViewModel() {
        return new ViewModelProvider(this).get(getVmClazz(this));
    }

    private View initViewDataBind() {
        // 利用反射 根据泛型得到 ViewDataBinding
        mDatabind = inflateBinding(this);
        return mDatabind.getRoot();
    }


    public abstract void initView(Bundle savedInstanceState);

    public abstract void onBindViewClick();

    public abstract void initObserver();

    protected abstract ViewGroup getAgentWebParent();

    protected abstract String getUrl();
}
